import re

from django.utils.deprecation import MiddlewareMixin
from mac import models
from django.conf import settings
from django.shortcuts import redirect, HttpResponse


class Mac(object):
    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        current_url = request.path_info
        mac_obj = Mac()
        username = request.session.get('user_info', 0)
        permission_list = request.session.get('permission_list', [])
        if username:
            user_obj = models.UserInfo.objects.filter(id=str(username['id']), username=username['name']).first()
            mac_obj.user = user_obj
        request.mac = mac_obj

        # 白名单：没有登录都可以访问的url
        for item in settings.WHITE_REGEX_URL_LIST:
            if re.match(item, current_url):
                return

        # 是否登入
        if not request.mac.user:
            return redirect('mac_login')

        # 是否有权访问
        flag = False
        for item in permission_list:
            reg = '^%s' % item.get('permission_url')
            if re.match(reg, current_url):
                flag = True
                break
        if not flag:
            return HttpResponse('无权访问')


